package com.gipson.amc.config.security;

import com.alibaba.fastjson.JSONObject;
import com.dsbj.common.msg.ResponseMessage;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginAuthFilter extends FormAuthenticationFilter {

    private Logger log = LoggerFactory.getLogger(LoginAuthFilter.class);

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if (isLoginRequest(request, response)) {
            if (isLoginSubmission(request, response)) {
                if (log.isTraceEnabled()) {
                    log.trace("Login submission detected.  Attempting to execute login.");
                }
                return executeLogin(request, response);
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Login page view.");
                }
                return true;
            }
        } else {
            HttpServletRequest httpRequest = WebUtils.toHttp(request);

            Subject subject=getSubject(request,response);
            // 如果是记住我登录的，则需要处理一下
            // isRemembered为true、isAuthenticated为false
            if(!subject.isAuthenticated() && subject.isRemembered()){
                // 通过记住我第一次进程序，并且保存的principal中有内容，添加用户到session
                if(subject.getSession().getAttribute("currentUser")==null && subject.getPrincipal() != null){
                    subject.getSession().setAttribute("currentUser",subject.getPrincipal());
                }
                return true;
            }

            if (isAjax(httpRequest)) {
                HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
                httpServletResponse.setCharacterEncoding("UTF-8");
                httpServletResponse.setContentType("application/json");
                httpServletResponse.getWriter().write(JSONObject.toJSONString(ResponseMessage.error("用户登录已超时,请重新登录!")));
                return false;
            } else {
                if (log.isTraceEnabled()) {
                    log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
                            "Authentication url [" + getLoginUrl() + "]");
                }
                saveRequestAndRedirectToLogin(request, response);
            }

            return false;
        }


    }

    /*
     * 判断ajax请求
     * @param request
     * @return
     */
    boolean isAjax(HttpServletRequest request){
        return  (request.getHeader("X-Requested-With") != null  && "XMLHttpRequest".equals( request.getHeader("X-Requested-With").toString())   ) ;
    }
}
